﻿using System;

namespace Ewk.Math.ComputationTypes.Computables
{
    class ComputableDouble : Computable<double>
    {
        #region Constructors
        public ComputableDouble()
        {
        }

        public ComputableDouble(double value)
            : base(value)
        {
        }
        #endregion

        #region ComputableBase implementations
        public override Computable<double> Add(Computable<double> other)
        {
            if (other != null)
            {
                Value += other.Value;
            }

            return this;
        }

        public override Computable<double> Subtract(Computable<double> other)
        {
            if (other != null)
            {
                Value -= other.Value;
            }

            return this;
        }

        public override Computable<double> Multiply(Computable<double> other)
        {
            if (other != null)
            {
                Value *= other.Value;
            }
            else
            {
                Value = Factory.Zero.Value;
            }

            return this;
        }

        public override Computable<double> Divide(Computable<double> other)
        {
            if (other == null)
            {
                throw new DivideByZeroException();
            }

            Value /= other.Value;
            return this;
        }

        public override Computable<double> Sqrt()
        {
            Value = System.Math.Sqrt(Value);
            return this;
        }

        public override Computable<double> Pow(Computable<double> power)
        {
            Value = power == null
                        ? Factory.One.Value
                        : System.Math.Pow(Value, power.Value);

            return this;
        }

        #endregion

        public override bool AlmostEquals(Computable<double> other)
        {
            return System.Math.Round(System.Math.Abs(Value - other.Value), 14) < double.Epsilon;
        }
    }
}
